import React, { Component } from 'react'
import { load, load_page } from '../reducers/post'
import { connect } from 'react-redux'
import SimplePageComponent from '../components/SimplePageComponent'


class PostList extends Component {

  constructor() {
    super(...arguments)
    this.jumpToPage = this.jumpToPage.bind(this) 
  }

  renderPost (item) {
    return (
      <div key={item._id}> 
        {item.title} 
      </div>
    )
  }

  // page_num starts from 0
  jumpToPage (page_num) {
    console.log('hello, jumping page')
    this.props.load_page(page_num)
  }

  componentDidMount() {
    this.props.load_page(this.props.params.pageId)
  }

  render() {

    const {loaded, loading, pages, page, items, load, load_page, login_func_action} = this.props;

    return (

      <div>

        <div className = 'row'>
          <div className="col-lg-12">
            <div className = 'page-header'>
              <h3>Container: PostPage ( This is different with PostList, in PostPage, you can query page number in the url, but in PostPage, you cannot.)</h3>
            </div>
          </div>
        </div>

        <div className = 'row'>

          <div className="col-lg-12">

            <h2>
              {loaded && <div className = 'label label-success'>Posts Loaded.</div>}
            </h2>

            <h2>
              {!loaded && !loading &&  <div className = 'label label-warning'>Posts Not Loaded. Click the Arrow of Pagination to Load Data.</div>}
            </h2>

            <h2>
              {loading && <div className = 'label label-info'>Posts Loading (takes 1 second)</div>}
            </h2>


          </div>

        </div>

        <br/>
        <div>{items.map(this.renderPost)} </div>

        <SimplePageComponent
          toPageFromParent = {this.jumpToPage}
          pages = {pages}
          page = {page} /> 

      </div>

      
    )
  }
}

function mapStateToProps(state, ownProps) {
  const {
    post: { loaded, loading, pages, page, items },
  } = state

  return {
    loaded,
    loading,
    pages,
    page,
    items,
  }
}

export default connect(mapStateToProps, {load, load_page})(PostList)